package com.vichat.common.util;

import org.springframework.web.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieUtil {
	/**
	 * 根据名称读取Cookie
	 * 
	 */
	public static String readCokie(HttpServletRequest request, HttpServletResponse response, String name)  {
		String value = null;
		try {

			if (name != null) {
				Cookie cookies[] = request.getCookies();
				if (cookies != null && cookies.length >= 2) {
					for (int i = 0; i < cookies.length; i++) {
						Cookie cookie = cookies[i];
						if (name.equals(cookie.getName())) {
							value = cookie.getValue();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	/**
	 * 清空cookie
	 */
	public static void clearCokie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	/**
	 * 写Cookie
	 */
	public static void writeCokie(HttpServletResponse response, String name, String value, int days) {
		try {
			int day = 24 * 60 * 60;
			Cookie cookie = new Cookie(name, value);
			cookie.setMaxAge(days * day);
			response.addCookie(cookie);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


    public static void create(HttpServletResponse httpServletResponse, String name, String value, Boolean secure, Integer maxAge, String domain) {
        Cookie cookie = new Cookie(name, value);
        //secure=true : 只工作于HTTPS
        cookie.setSecure(secure);
        //对JavaScript不可见
        cookie.setHttpOnly(true);
        //maxAge=0：cookie现在过期,maxAge<0：在浏览器退出时过期。
        cookie.setMaxAge(maxAge);
        //仅在域可见
        cookie.setDomain(domain);
        //所有路径都可见
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
    }
    public static void clear(HttpServletResponse httpServletResponse, String name , String domain) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0);
//        cookie.setDomain(domain);
        httpServletResponse.addCookie(cookie);
    }

    public static String getValue(HttpServletRequest httpServletRequest, String name) {
        Cookie cookie = WebUtils.getCookie(httpServletRequest, name);
        return cookie != null ? cookie.getValue() : null;
    }
}
